//
//  Founction.m
//  OCBase
//
//  Created by 侯伟 on 2019/8/23.
//  Copyright © 2019 侯伟. All rights reserved.
//

#import "Founction.h"


#import <CommonCrypto/CommonDigest.h>

@implementation Founction

/**
 判断手机号
 
 @param mobileNumber 手机号
 @return 是否为手机号
 */
+(BOOL)isMobileNumber:(NSString *)mobileNumber{
    
    NSString *MOBILE = @"^[1][0-9][0-9]{9}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:mobileNumber];
}

/**
 判断是否符合规定的密码格式
 
 @param password 字符串
 @return 是否符合
 */
+ (BOOL)isSafePassword:(NSString *)password{
    
    NSString *passWordRegex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passWordRegex];
    
    if ([regextestcm evaluateWithObject:password] == YES){
        return YES;
    }
    return NO;
}

/**
 校验身份证号码
 
 @param idCard 身份证号码
 @return -
 */
+ (BOOL)idCardNo:(NSString *)idCard{
    
    //判断是否为空
    if (!idCard.length) {
        return NO;
    }
    //判断是否是18位，末尾是否是x
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    if(![identityCardPredicate evaluateWithObject:idCard]){
        return NO;
    }
    //判断生日是否合法
    NSRange range = NSMakeRange(6,8);
    NSString *datestr = [idCard substringWithRange:range];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : @"yyyyMMdd"];
    if([formatter dateFromString:datestr]==nil){
        return NO;
    }
    
    //判断校验位
    if(idCard.length==18){
        
        NSArray *idCardWi= @[ @"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2" ]; //将前17位加权因子保存在数组里
        NSArray * idCardY=@[ @"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2" ]; //这是除以11后，可能产生的11位余数、验证码，也保存成数组
        int idCardWiSum=0; //用来保存前17位各自乖以加权因子后的总和
        for(int i=0;i<17;i++){
            idCardWiSum+=[[idCard substringWithRange:NSMakeRange(i,1)] intValue]*[idCardWi[i] intValue];
        }
        
        int idCardMod=idCardWiSum%11;//计算出校验码所在数组的位置
        NSString *idCardLast=[idCard substringWithRange:NSMakeRange(17,1)];//得到最后一位身份证号码
        
        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
        if(idCardMod==2){
            if([idCardLast isEqualToString:@"X"] || [idCardLast isEqualToString:@"x"]){
                return YES;
            }else{
                return NO;
            }
        }else{
            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
            if([idCardLast intValue]==[idCardY[idCardMod] intValue]){
                return YES;
            }else{
                return NO;
            }
        }
    }
    return NO;
}

/// 邮箱验证
/// @param email -
+ (BOOL)isEmail:(NSString *)email{
    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [emailTest evaluateWithObject:email];
}



/**
 用户姓名验证
 
 @param fullName 姓名
 @return -
 */
+ (BOOL)isVaildFullName:(NSString *)fullName{

    NSString* name = [fullName stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (!name.length)
        return NO;
    
    NSRange range1 = [name rangeOfString:@"·"];
    NSRange range2 = [name rangeOfString:@"•"];
    if(range1.location != NSNotFound ||   // 中文 ·
       range2.location != NSNotFound )    // 英文 •
    {
        //一般中间带 `•`的名字长度不会超过15位，如果有那就设高一点
        if ([name length] < 2 || [name length] > 10)
        {
            return NO;
        }
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[\u4e00-\u9fa5]+[·•][\u4e00-\u9fa5]+$" options:0 error:NULL];
        
        NSTextCheckingResult *match = [regex firstMatchInString:name options:0 range:NSMakeRange(0, [name length])];
        
        NSUInteger count = [match numberOfRanges];
        
        return count == 1;
    }
    else
    {
        //一般正常的名字长度不会少于2位并且不超过8位，如果有那就设高一点
        if ([name length] < 2 || [name length] > 10) {
            return NO;
        }
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[\u4e00-\u9fa5]+$" options:0 error:NULL];
        
        NSTextCheckingResult *match = [regex firstMatchInString:name options:0 range:NSMakeRange(0, [name length])];
        
        NSUInteger count = [match numberOfRanges];
        
        return count == 1;
    }
}

+ (NSString *)md5:(NSString *)string
{
    const char *cStr = [string UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
    
    return [[NSString stringWithFormat:
             @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}

+ (NSTimeInterval)dateStringToTimeInterval:(NSString *)dateStr
{
    NSDate* date = [NSDate dateFromString:dateStr];
    return date.timeIntervalSince1970;
}

+ (BOOL)openURLString:(NSString *)urlStr{
    
    NSURL *url = [NSURL URLWithString:urlStr];
    return [Founction openURL:url];
}

+ (BOOL)openURL:(NSURL *)url{
    
    if(!url)
        return NO;
    
    if(![[UIApplication sharedApplication] canOpenURL:url]){
        return NO;
    }
    
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:NULL];
        return YES;
    } else {
        return [[UIApplication sharedApplication] openURL:url];
    }
}

/**
 拨打电话
 
 @param number 正确的手机号码
 */
+ (void)callTelphone:(NSString *)number{
    
    if (number == NULL || [number length] == 0){
        return;
    }
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",number]] options:@{} completionHandler:^(BOOL success) {
        
    }];
}

@end
